<template>
	<view class="navigation">
		<view class="top-view">
			<eui-nav-bar ref="BcmNavBar" title="订单处理" :storeName="sUserStoreName" :storeId="sUserStore"
				@onClickStore="clickStore" color="#333" backgroundColor="white" @onClickRefresh="onClickRefresh">
				<template #storeExtend>
					<view style="flex: 1;font-size:0.75rem;padding-left: 20rpx;" class="text-ellipsis text-center"
						@click="showUserMerchantModal" v-if="sUserMerchantCode">[{{
							sUserMerchantCode }}]{{ sUserMerchantName }} ></view>
				</template>
				<template #popupContent>
					<eui-card-input v-model="formData.sortType" :range="selectorList" title="设置排序方式"
						rightIconType="right" type="radio" alignType="left" style="margin-top: 10rpx;"
						@buttonClick="selectSortType" />
				</template>
			</eui-nav-bar>
			<view
				style="height: 100rpx;width: 100%;background-color: #fff;padding: 7rpx 50rpx 20rpx 17rpx;box-sizing: border-box;font-size: 32rpx;"
				class="flex align-center">
				<view
					style="width: 50%;background-color: #E3E3E3;padding: 6rpx;box-sizing: border-box;border-radius: 10rpx;height: 100%;"
					class="flex just-between align-center">
					<view style="border-radius: 10rpx;width: 50%;height: 100%;font-weight: bold;"
						:class="orderType == 'on' ? 'flex align-center just-center co-00 bg-white' : 'flex align-center just-center co-51'"
						@click="swichTab">
						进行中
					</view>
					<view style="border-radius: 10rpx;width: 50%;height: 100%;font-weight: bold;"
						:class="orderType == 'all' ? 'flex align-center just-center co-00 bg-white' : 'flex align-center just-center co-51'"
						@click="swichTab">
						全部订单
					</view>
				</view>
				<view class="flex align-center" style="height: 100%;width: 50%;box-sizing: border-box;">
					<Popover :contents="[{
						text: '搜订单',
						showBtn: true
					}, {
						text: '搜售后单',
						showBtn: true
					}]" theme="light" placement="bottom" @select="onSelectOrderType" width="200">
						<template v-slot:reference>
							<view class="flex align-center just-center"
								style="background: #F1F1F1;border-radius: 40px;color: #8B8B8B;height: 77rpx;width: 200rpx;margin: 0 50rpx;">
								<text>搜索</text><eui-uicons class="m-card-arrow" type="down" size="30"
									style="color: #8B8B8B !important;"></eui-uicons>
							</view>
						</template>
					</Popover>
					<icon class="icon enjoyIcon icon-saoyisao1" v-on:tap="scanCode" style="font-size: 50rpx;" />
				</view>
			</view>
			<view class="container">
				<scroll-view class="scroll-view" scroll-x scroll-with-animation scroll-animation-duration="240"
					v-if="orderType == 'on'">
					<view :class="tabIndex == index ? 'item on' : 'item'" v-for="(item, index) in statusList"
						:key="index" @click="changeTab1(index)">
						<view class="name">{{ item.text }}</view>
						<view class="border"
							:style="{ 'background': tabIndex == index ? 'linear-gradient(159deg, #4FE0EA 0%, #85B6FD 100%)' : 'transparent' }">
						</view>
						<view class="number" v-if="item.number > 0 && item.number < 100">{{ item.number }}</view>
						<view class="number" v-if="item.number >= 100">99+</view>
					</view>
				</scroll-view>
				<view v-else class="flex search">
					<view style="flex:1;" class="flex align-center">
						<eui-datetime-picker type="date" v-model="searchData.startDate" placeholder="选择日期"
							:border="false" @change="changeDate"
							style="background-color: transparent;font-size: 21rpx;" />
						<eui-uicons type="clear" size="30" v-if="searchData.startDate"
							class="m-card-arrow m-card-arrowright" @click="clear" />
						<eui-uicons type="down" size="20" class="m-card-arrow m-card-arrowright" v-else />
					</view>
					<view style="width:200rpx!important;"><eui-card-input v-model="searchData.status" title=""
							:colon="false" type="selector" rightIconType="right" rightIconSize='20' alignType="left"
							:range="[{ text: '全部状态', value: '' }].concat(statusRange)" @buttonClick="selectStatus"
							style="flex:1;text-align: right" /></view>
					<view style="width:200rpx!important;"><eui-card-input v-model="searchData.chnlType" title=""
							alignType="left" :colon="false" type="selector" rightIconType="right" rightIconSize='20'
							style="flex:1" @buttonClick="selectChnlType"
							:range="[{ text: '全部渠道', value: '' }].concat(chnlTypeList)" /></view>
				</view>
			</view>
			<view class="container1"
				v-if="statusList.length > 0 && statusList[tabIndex].list.length > 0 && orderType == 'on'">
				<scroll-view class="scroll-view" scroll-x scroll-with-animation scroll-animation-duration="240"
					v-if="orderType == 'on'">
					<view :class="activeKey.value == item.value ? 'item1 on1' : 'item1'"
						v-for="(item, index) in statusList[tabIndex].list" :key="index"
						@click="changeTab(item.value, item.type)">
						<view class="name">{{ item.text }}</view>
						<view class="number1" v-if="item.number > 0 && item.number < 100">{{ item.number }}</view>
						<view class="number1" v-if="item.number >= 100">99+</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="main-view" :style="{ height: listHeight + 'rpx' }">
			<eui-virtual-list @onRefresh="listPullDown" @lower="listPullUp" refresher="true" isBottom="true"
				:origList="orderList" type="list" :showHeard="false">
				<template v-slot:list="scope">
					<OrderItem v-if="scope.orderId" :scope="scope" :currentTime="currentTime"
						:chnl-type-list="chnlTypeDictList" :order-status-list="orderStatusList"
						:delivery-status-list="deliveryStatusList" :pick-type-list="pickTypeList"
						v-model:showContactPop="showContactPop" v-model:logisticsCode="logisticsCode"
						v-model:deliverList="deliverList" :logistics-code-list="logisticsCodeList"
						:order-action="orderAction" v-model:showDeliveryPop="showDeliveryPop"
						v-model:showShipPhonePop="showShipPhonePop" :delivery-time-type-list="deliveryTimeTypeList"
						v-model:showPop="showPop" v-model="orderItem" @print="orderItemPrint"
						:showConfigModal="showConfigModal" />
					<AfsOrderItem v-if="scope.afsOrderId" :scope="scope" :order-action="orderAction"
						:current-time="currentTime" :afs-order-status-list="afsOrderStatusList"
						:return-goods-type-list="returnGoodsTypeList" :deal-type-list="dealTypeList"
						v-model:showContactPop="showContactPop" v-model:logisticsCode="logisticsCode"
						v-model:deliverList="deliverList" v-model:showPop="showPop" v-model="orderItem"
						v-model:showDeliveryPop="showDeliveryPop" v-model:showShipPhonePop="showShipPhonePop"
						:chnl-type-list="chnlTypeDictList" :delivery-status-list="deliveryStatusList"
						:logistics-code-list="logisticsCodeList" @print="afsOrderItemPrint"
						:showConfigModal="showConfigModal" />
				</template>
				<template v-slot:bottom="scope">
					<view v-show="scope.orderId || scope.afsOrderId" class="flex align-center">
						<OrderOperateBtn :scope="scope" @close="close" @fetchData="fetch"
							@orderItemPrint="orderItemPrint" v-model:currentItem="currentItem" v-model="orderItem"
							v-model:showOrderPickupPop="showOrderPickupPop" v-model:modalType="modalType"
							v-model:showCancelOrderPopup="showCancelOrderPopup" v-model:isOrderCancel="isOrderCancel"
							v-model:title="title" v-model:showDeliveryCancelPopup="showDeliveryCancelPopup"
							v-model:showAuditSendAfsPopup="showAuditSendAfsPopup" v-model:dealType="dealType"
							v-model:dealList="dealList" v-model:showConfirmApplyOrderPopup="showConfirmApplyOrderPopup"
							v-model:billType="billType" :showConfigModal="showConfigModal" />
					</view>
				</template>
			</eui-virtual-list>

			<!-- 顾客地址弹窗 -->
			<CustAddressPopup :show="showPop" :scope="orderItem" @close="showPop = false" :title="popupTitleType"
				:addressKey="addressKey" />
			<!-- 联系顾客弹窗 -->
			<CustContactPopup :show="showContactPop" :scope="orderItem" @close="showContactPop = false"
				:orderType="popupOrderType" />
			<!-- 物流信息弹窗 -->
			<DeliveryPopup :show="showDeliveryPop" :scope="orderItem" @close="closeDeliveryPopup"
				:deliverList="deliverList" :logisticsCode="logisticsCode" :orderType="popupOrderType" />
			<!-- 配送员弹窗 -->
			<ShipContactPopup :show="showShipPhonePop" :scope="orderItem" @close="showShipPhonePop = false" />
			<!-- 拣货弹窗 -->
			<OrderPickPopup :show="showOrderPickupPop" :scope="orderItem" @close="showOrderPickupPop = false"
				@orderAction="orderAction" />
			<!-- 取消配送弹窗 -->
			<DeliveryCancelPopup :show="showDeliveryCancelPopup" @close="showDeliveryCancelPopup = false"
				:scope="orderItem" @select="selectDeliveryCancelItem" @inputchange="inputDeliveryChange"
				:billType="billType">
				<template v-slot="">
					<view class="bottom-1">
						<eui-button type="primary" title="确认" style="width: 50%;" singleTag="deliveryCancelSure"
							@click="deliveryCancelSure" />
					</view>
				</template>
			</DeliveryCancelPopup>
			<!-- 取消订单、拒单、驳回入库申请弹窗 -->
			<CancelOrderPopup :show="showCancelOrderPopup" @close="showCancelOrderPopup = false" :scope="orderItem"
				:title="title" :modalType="modalType" :dealList="dealList"
				:orderCancelReasonType="orderCancelReasonType" @select="selectItem" @inputchange="inputChange">
				<template v-slot="">
					<view class="bottom-1">
						<eui-button type="primary" title="确认" style="width: 50%;"
							@click="orderSureCancel(orderItem, modalType, isOrderCancel, dealType, orderCancelReasonType, rejectReason, orderAction, showConfigModal)" />
					</view>
				</template>
			</CancelOrderPopup>
			<!-- 退货退款审核弹窗 -->
			<AuditSendAfsPopup :show="showAuditSendAfsPopup" @close="showAuditSendAfsPopup = false" :scope="orderItem"
				@submit="submitAuditSendAfs" />
			<!-- 售后审核弹窗 -->
			<ConfirmApplyOrderPopup :show="showConfirmApplyOrderPopup" @close="showConfirmApplyOrderPopup = false"
				@orderAction="acceptAfsApplyOrder"
				@updateConfirmApply="showConfirmApplyOrderPopup = false; showAuditSendAfsPopup = true"
				:scope="orderItem">
			</ConfirmApplyOrderPopup>
		</view>
		<view style="text-align: center;width: 100%;height: 70rpx;line-height: 70rpx;background-color: aliceblue;"
			v-if="showMessage">{{ showMessageValue }} <text style="margin-left: 10rpx;color:orange"
				@click.stop="toPrinterSet">去设置</text>
		</view>
	</view>
</template>
<script setup lang="js">
import { ref, onUnmounted, computed, watch } from 'vue';
import service from '@/common/service';
import { getBcmUrl, bcmRequest } from '../../../hooks/bcmServices';
import { useBcmConfig } from '../../../hooks/useBcmConfig';
import { getBcmDictLists, getBcmDictItem } from '../../../hooks/bcmUseUntils';
import Guid from '../../../common/guid.ts';
import { orderSureCancel } from './utils/cancelOrder.js'
import { onLoad, onShow } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import { useMainStore } from "@/store/modules/store";
import { usePrinterStore } from "@/store/printerStore";
import { useReminderStore } from "@/store/reminderStore";
import useVoiceTaskStore from "@/store/useVoiceTaskStore";
import { pickingOrderStore } from "@/store/pickingOrderStore";
import { usePrintTaskStore } from "@/store/usePrintTaskStore";
import { handleGetVoiceTypeItem } from "@/common/Voice";
import BluetoothPrinter from '@/common/BluetoothPrinter';
import { init, onClickRefresh } from '../../../hooks/bcmInit';
import { getPrintData } from '../utils/PrintFormatUtil.js'
import Enjoy from "../../../common/enjoy"
import OrderItem from './components/OrderItem.vue'
import AfsOrderItem from './components/AfsOrderItem.vue'
import OrderOperateBtn from './components/OrderOperateBtn.vue'
import CustContactPopup from './components/CustContactPopup.vue'
import CustAddressPopup from './components/CustAddressPopup.vue'
import DeliveryPopup from './components/DeliveryPopup.vue'
import ShipContactPopup from './components/ContactShipPopup.vue'
import OrderPickPopup from './components/OrderPickPopup.vue'
import DeliveryCancelPopup from './components/DeliveryCancelPopup.vue'
import CancelOrderPopup from './components/CancelOrderPopup.vue'
import AuditSendAfsPopup from './components/AuditSendAfsPopup.vue'
import ConfirmApplyOrderPopup from './components/ConfirmApplyOrderPopup.vue'
import Popover from '../components/Popover.vue'
import BcmEventType from "../common/BcmEventType";

const mainStore = useMainStore();
const { loginInfo } = mainStore;
const printerStore = usePrinterStore();
const reminderStore = useReminderStore();
const { addVoiceTask } = useVoiceTaskStore();
const { addTask } = usePrintTaskStore();
const pickingStore = pickingOrderStore();
const { sortType } = storeToRefs(pickingStore);
const { getBcmConfigValue, bcmConfig } = useBcmConfig();
const { printTimes, autoPrint, bluetoothPrinter } = storeToRefs(printerStore);
const { enable, voiceStyle, playTimes } = storeToRefs(reminderStore);

const bcmUrl = getBcmUrl()
const showConfigModal = ref(false);
const timer = ref(null)
const time = ref(null)
const currentTime = ref(null)
const heartBeatInterval = ref(null)

const showMessage = ref(false)
const showMessageValue = ref('')

const BcmNavBar = ref(null);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const sUserMerchantCode = ref('');
const sUserMerchantName = ref('');

const CurrentPage = ref(1); //第几页
const PageSize = ref(5); //每页10条
const RowsCount = ref(0); //总条数
const PageCount = ref(1); //总页数
const orderList = ref([]);

const statusList = ref([]);
const tabIndex = ref(0)
const formData = ref({
	chnlType: '',
	orderNo: '',
	status: '1',
	startDate: null,
	endDate: null,
	sortType: '21'
})
const searchData = ref({
	chnlType: '',
	status: '',
	startDate: null,
	endDate: null,
})
const statusRange = ref([{
	text: '进行中',
	value: '1,2,3,4,5,25,9'
}, {
	text: '已完成',
	value: '7'
}, {
	text: '已取消',
	value: '8'
}])
const activeKey = ref({
	type: '0',
	value: '1,2'
})

const selectorList = ref([
	{ value: '10', text: "下单时间正序" },
	{ value: '11', text: "下单时间逆序" },
	{ value: '20', text: "拣货剩余时长正序" },
	{ value: '21', text: "预计送达时间正序" }
])

const chnlTypeList = ref([])
const orderStatusList = ref([])
const deliveryStatusList = ref([])
const pickTypeList = ref([])
const deliveryTimeTypeList = ref([])
const logisticsCodeList = ref([])
const afsOrderStatusList = ref([])
const dealTypeList = ref([])
const returnGoodsTypeList = ref([])
const chnlTypeDictList = ref([])
const orderPrimaryStatusList = ref([]);
const performanceStatusList = ref([]);
const listHeight = ref(300);  //列表高度

const showDeliveryCancelPopup = ref(false)
const showPop = ref(false)
const showContactPop = ref(false)
const showShipPhonePop = ref(false)
const showDeliveryPop = ref(false)
const showOrderPickupPop = ref(false)
const isOrderCancel = ref(false)
const showCancelOrderPopup = ref(false)
const showAuditSendAfsPopup = ref(false)
const showConfirmApplyOrderPopup = ref(false)

const isPrinting = ref(false)
const isSkip = ref(false)
const billType = ref('1')

const printOrderList = ref([])
const isPrint = ref(false)

const orderType = ref('on')
const orderCancelReasonType = ref('')
const rejectReason = ref('')
const orderDeliveryCancelReasonType = ref(null)
const orderDeliveryCancelReason = ref('')
const orderItem = ref({})
const currentItem = ref({})
const modalType = ref('cancel')
const title = ref('取消订单原因')
const dealType = ref('3')
const dealList = ref([])
const deliverList = ref([])
const logisticsCode = ref('')
const isMp3Played = ref(false)
const BcmPrintTerminalId = ref('')
const WsRef = ref(null)
const reconnectAttempts = ref(0)

const clear = () => {
	changeDate(null)
}

const startTimer = () => {
	stopTimer();
	timer.value = setInterval(() => {
		currentTime.value = new Date().getTime();
	}, 1000);
}

const stopTimer = () => {
	// 停止定时器
	clearInterval(timer.value);
	timer.value = null;
}

const toPrinterSet = function () {
	uni.navigateTo({
		url: '/pages/MainViews/user/setting/printSetting'
	});
}

const connectWebSocket = function () {
	let loginInfo = service.getStorageSync('login_data');
	let socketUrl = bcmUrl.wsApi.replace("http:", "");
	const wsUrl = 'ws:' + socketUrl + '?access_token=' + loginInfo.access_token;
	const ws = uni.connectSocket({
		url: wsUrl,
		success: () => {
			console.log('WebSocket connection established.');
		},
		fail: (err) => {
			console.error('WebSocket connection failed:', err);
		}
	});
	WsRef.value = ws;
	if (service.getStorageSync('pushMode') != '1') {
		initWs()
	}
}
const initWs = function () {
	WsRef.value.onOpen((res) => {
		handleWsOpen()
		startHeartbeat()

		console.log('WebSocket connection opened.');
	});

	WsRef.value.onMessage((res) => {
		handleMessage(res);
	});

	WsRef.value.onError((err) => {
		console.error('WebSocket error:', err);
		retryConnection()
	});

	WsRef.value.onClose(() => {
		console.log('WebSocket connection closed.');
	});
}

const retryConnection = () => {
	if (reconnectAttempts.value < 5) {
		setTimeout(() => {
			reconnectAttempts.value++;
			initWs();
		}, 3000);
	} else {
		console.log('websocket错误错误错误....')
	}
}

const handleWsOpen = function () {
	if (sUserStore.value) {
		WsRef.value.send({
			data: JSON.stringify({ storeCode: sUserStore.value, terminalType: "APP", terminalId: BcmPrintTerminalId.value })
		})
	}

}
const handleMessage = async function (event) {
	let messageObject = JSON.parse(JSON.parse(event.data)?.Payload);
	if (!!messageObject && messageObject?.messageType != 'terminalHeartbeat') {
		if (['newOrder', 'newPreOrder', 'orderCancelApply', 'orderRefundApply'].includes(messageObject.messageType)) {
			if (messageObject.message.length && autoPrint.value) {
				let idList = messageObject.message?.map(v => v.orderNo || v.afsOrderNo)
				let a;
				if (messageObject?.message?.length && messageObject.message[0].orderNo) {
					a = await handlePreQueryOrderPrint(idList);
					await Promise.all(a?.map(async v => {
						await addPrintTaskFn(v, 'order', true)
					}))
				}
				if (messageObject?.message?.length && messageObject.message[0].afsOrderNo) {
					a = await handlePreQueryAfsOrderPrint(idList);
					await Promise.all(a?.map(async v => {
						await addPrintTaskFn(v, 'afs', true)
					}))
				}
			}
		}
		if (enable.value) {
			(Guid.NewGuid().ToString(), messageObject?.messageType)
		}
		debounce()
	}
}

let timeout;
const debounce = (type = 1) => {
	if (timeout) {
		clearTimeout(timeout)
	}
	if (type === 2) {
		console.log("update事件触发更新");
	}
	timeout = setTimeout(() => {
		console.log('...执行了消息推送刷新')
		if (orderType.value == 'on') {
			changeTab(activeKey.value.value, activeKey.value.type)
		} else {
			fetchAllSearchData()
		}
	}, 1000)
}

const addVoiceTaskFn = function (id, v) {
	let voice = handleGetVoiceTypeItem(v)
	if (!!voice) {
		addVoiceTask({
			id,
			path: 'static/audio/' + voiceStyle.value + '/' + voice.file,
			times: playTimes.value[voice.name] ? playTimes.value[voice.name] : 1
		})
	}
}

const handlePreQueryOrderPrint = async function (idList) {
	let params = {
		storeCode: sUserStore.value,
		orderNoList: idList,
		operateMode: '自动',
		operateTerminal: 'APP'
	}
	const response = await bcmRequest(bcmUrl.orderApi, '订单表', 'PreQueryOrderAutoPrint', params);
	let arr = []
	response?.filter(v => v.status == '1')?.map(v => {
		arr.push(v.bcmOrder)
	})
	return arr
}

const handlePreQueryAfsOrderPrint = async function (idList) {
	let params = {
		storeCode: sUserStore,
		afsOrderNoList: idList,
		operateMode: '自动',
		operateTerminal: 'APP'
	}
	const response = await bcmRequest(bcmUrl.orderApi, '售后单表', 'PreQueryAfsOrderAutoPrint', params);
	let arr = []
	response?.filter(v => v.status == '1')?.map(v => {
		arr.push(v.bcmAfsOrder)
	})
	return arr
}

const addPrintTaskFn = function (v, type = 'order', isAutoPrint = false) {
	let added = addTask({
		id: type == 'order' ? v.orderNo : v.afsOrderNo,
		task: async () => await handleTaskPrint(v, type, isAutoPrint)
	})
	if (!isAutoPrint) {
		let text = added ? '已加入打印队列' : '已在打印队列中，请勿重复操作';
		uni.showToast({
			title: text,
			icon: 'none'
		});
	}
}

const handleTaskPrint = function (order, type, isAutoPrint = false) {
	return new Promise((resolve, reject) => {
		let data = getPrintData(order, type, printTimes.value), skip = isAutoPrint ? '0' : (isSkip.value ? '1' : '0');
		// console.log(order, 'data')
		BluetoothPrinter.setDevice(bluetoothPrinter.value).checkAndPrint(data).then((res) => {
			if (res.code == '0') {
				if (type == 'afs') {
					ConfirmAfsOrderPrint(order, skip, isAutoPrint)
				} else {
					ConfirmOrderPrint(order, skip, isAutoPrint)
				}
			}
			resolve()
		}).catch(res => {
			if (!isAutoPrint) {
				skipFunc(res?.msg, order, type);
			}
			console.warn("handleTaskPrint:catch", res);
			reject();
		})
	})
}

const skipFunc = function (contenet = '打印失败，是否跳过打印流程进行后续操作？', order, type) {
	uni.showModal({
		title: '提示',
		content: contenet,
		showCancel: true,
		mask: true,
		success: (res) => {
			if (res.confirm) {
				isSkip.value = true;
				isPrinting.value = false;
				if (type === 'afs') {
					ConfirmAfsOrderPrint(order, '1', false)
				} else {
					ConfirmOrderPrint(order, '1', false)
				}
			} else {
				skipReset()
			}
		}
	})
}

const setPrint = function (v, type, isAutoPrint = false) {
	return new Promise((resolve, reject) => {
		if (mainStore.enjoyServiceIp && mainStore.enjoyServiceIp.EnjoyBCM) {
			if (!isAutoPrint || (autoPrint.value && isAutoPrint)) {
				if (!bluetoothPrinter.value?.deviceId) {
					skipFunc("未设置蓝牙打印机，是否跳过打印？", v, type)
					return;
				}
				addPrintTaskFn(v, type, isAutoPrint)
			} else {
				console.log("当前未设置蓝牙打印机");
			}
		}
	})
}

const skipReset = () => {
	isPrinting.value = false;
	isSkip.value = false;
}

const ConfirmAfsOrderPrint = (v, skipPrintFlag = '0', operateMode = undefined) => {
	orderAction({
		uniqueKey: '售后单表',
		methodName: 'ConfirmAfsOrderPrint'
	}, v, {
		afsOrderNo: v.afsOrderNo,
		afsOrderId: v.afsOrderId,
		BillId: v.afsOrderId,
		thirdAfsOrderNo: v.thirdAfsOrderNo,
		extras: {
			operateMode: operateMode ? '自动' : '手动',
			operateTerminal: 'APP',
			skipPrintFlag
		}
	})
}

const ConfirmOrderPrint = (v, skipPrintFlag = '0', operateMode = undefined) => {
	orderAction({
		uniqueKey: '订单表',
		methodName: 'confirmOrderPrint'
	}, v, {
		operateMode: operateMode ? '自动' : '手动',
		operateTerminal: 'APP',
		skipPrintFlag
	})
}

const orderItemPrint = function (v) {
	setPrint(v, 'order')
}

const afsOrderItemPrint = function (v) {
	setPrint(v, 'afs')
}

const initTerminalId = function () {
	let terminalId = service.getStorageSync('BcmPrintTerminalId')
	if (!terminalId) {
		BcmPrintTerminalId.value = Guid.NewGuid().ToString()
		service.setStorageSync('BcmPrintTerminalId', BcmPrintTerminalId.value)
	} else {
		BcmPrintTerminalId.value = terminalId;
	}
}

const startHeartbeat = function () {
	heartBeatInterval.value = setInterval(() => {
		console.log('Ws.readyState', WsRef.value.readyState)
		if (WsRef.value.readyState == '1') {
			WsRef.value.send({ data: 'heartbeat' });
			console.log('Sent heartbeat.', new Date());
		} else {
			console.log('ws.readyState', WsRef.value.readyState);
			stopHeartbeat()
			initWs()
		}
	}, 60000);
}

const stopHeartbeat = function () {
	if (heartBeatInterval.value) {
		clearInterval(heartBeatInterval.value);
		heartBeatInterval.value = null;
	}
}

const checkAutoPlay = function () {
	startAutoPlay();
}

const startAutoPlay = function () {
	stopAutoPlay(); // 先停止之前的定时器，避免重复执行
	time.value = setInterval(function () {
		fetchNewOrderNum().then((data) => {
			let a = 0, mp3Path = [], AutoPrint = false, AutoPrintAfsOrder = false, default_url = 'static/audio/default/';
			data?.map((v, index) => {
				if (v.status === '1' && v.number > 0) {
					a += 1;
					AutoPrint = true
					let newOrder = handleGetVoiceTypeItem('newOrder')
					mp3Path.push(default_url + newOrder.file);
				} else if (v.status === '9' && v.number > 0) {
					a += 1;
					let orderDeliveryException = handleGetVoiceTypeItem('orderDeliveryException')
					mp3Path.push(default_url + orderDeliveryException.file);
				} else if ((v.status === '1011' || v.status === '1012' || v.status ===
					'10') && v.number > 0) {
					a += 1;
					AutoPrintAfsOrder = true;
					let orderCancelApply = handleGetVoiceTypeItem('orderCancelApply')
					mp3Path.push(default_url + orderCancelApply.file)
				} else if ((v.status === '12' || v.status === '17') && v.number > 0) {
					a += 1;
					AutoPrintAfsOrder = true;
					let orderRefundApply = handleGetVoiceTypeItem('orderRefundApply')
					mp3Path.push(default_url + orderRefundApply.file);
				}
			})

			console.warn("语音播报------->待播报数量:mp3Path.length, enable.value, isMp3Played.value", mp3Path.length, enable.value, isMp3Played.value);
			if (mp3Path.length > 0 && enable.value && !isMp3Played.value) {
				// 按顺序播放音乐
				playMp3(mp3Path)
			}
			console.warn("fetchNewOrderNum------>autoPrint.value,sUserStore.value,AutoPrint,AutoPrintAfsOrder", autoPrint.value, AutoPrintAfsOrder, !!sUserStore.value, AutoPrint, AutoPrintAfsOrder)
			if ((AutoPrint || AutoPrintAfsOrder) && !!sUserStore.value) {
				if (autoPrint.value) {
					AutoPrint && aotoPrint()
					AutoPrintAfsOrder && autoPrintAfs()
				}
			}

			if (mp3Path.length > 0 && !!sUserStore.value && orderType.value !== 'all') {
				changeTab(activeKey.value.value, activeKey.value.type)
			}
		});
	}, 45000); // 每隔1分钟执行一次自动播放音乐
}

const aotoPrint = async function () {
	const param = {
		IsNotPage: false,
		// PageSize: 5,
		extras: {
			isQueryGoodsDetails: true
		},
		WhereList: [{
			c_col: "storeCode",
			c_oper: "等于",
			c_value: sUserStore.value,
			c_logic: "而且"
		}, {
			c_col: "orderStatus",
			c_oper: "等于",
			c_value: '2',
			c_logic: "而且"
		},
		{
			c_col: "isPrinted",
			c_oper: "等于",
			c_value: '0',
			c_logic: "而且"
		}
		]
	}
	const response = await bcmRequest(bcmUrl.orderApi, '订单表', 'EnjoyQueryList', param);
	if (response.ReturnObject.length > 0) {
		let list = [];
		response.ReturnObject?.map(v => {
			list.push({
				...v,
				type: 'order'
			})
		})
		printOrderList.value = mergeArrays(printOrderList.value, list)
		// console.warn('order2',printOrderList.value, isPrint.value);
		if (!isPrint.value) {
			isPrint.value = true;
			doingPrint();
		}
	}
}
const autoPrintAfs = async function () {
	const param = {
		IsNotPage: true,
		extras: {
			isQueryGoodsDetails: true
		},
		WhereList: [{
			c_col: "storeCode",
			c_oper: "等于",
			c_value: sUserStore.value,
			c_logic: "而且"
		},
		{
			c_col: "isPrinted",
			c_oper: "等于",
			c_value: '0',
			c_logic: "而且"
		},
		{
			c_col: "afsOrderStatus",
			c_oper: "包含",
			c_value: '10,12,17',
			c_logic: "而且"
		}
		]
	}
	const response = await bcmRequest(bcmUrl.orderApi, '售后单表', 'EnjoyQueryList', param);
	if (response.ReturnObject.length > 0) {
		let list = [];
		response.ReturnObject?.map(v => {
			list.push({
				...v,
				type: 'afs'
			})
		})
		printOrderList.value = mergeArrays(printOrderList.value, list)
		if (!isPrint.value) {
			isPrint.value = true;
			doingPrint();
		}
	}
}

const setPrint1 = function (v, type, isAutoPrint = false) {
	return new Promise((resolve, reject) => {
		if (mainStore.enjoyServiceIp && mainStore.enjoyServiceIp.EnjoyBCM) {
			if (!isAutoPrint || (autoPrint.value && isAutoPrint)) {
				if (!bluetoothPrinter.value?.deviceId) {
					skipFunc("未设置蓝牙打印机，是否跳过打印？", v, type)
					return;
				}

				let data = getPrintData(v, type, printTimes.value);
				isPrinting.value = true;
				if (!isAutoPrint) {
					// service.enjoyShowLoading("打印中...")
				}
				BluetoothPrinter.setDevice(bluetoothPrinter.value).checkAndPrint(data).then(res => {
					if (res.code == '0') {
						resolve()
					}
				}).catch(res => {
					if (!isAutoPrint) {
						skipFunc(res?.msg, v, type);
					}
				}).finally(res => {
					isPrinting.value = false;
					service.enjoyHideLoading();
				});
				init();
			} else {
				console.log("当前未设置蓝牙打印机");
				skipFunc("当前未设置蓝牙打印机，是否跳过打印？", v, type)
			}
		}
	})
}

const doingPrint = function () {
	console.log('doingPrint', printOrderList.value?.map(v => v.orderId || v.afsOrderId))
	if (printOrderList.value.length) {
		let item = printOrderList.value[0];
		if (item.type == 'order') {
			setPrint1(item, 'order', true).then(() => {
				ConfirmOrderPrint(item, '0')
				console.log(printOrderList.value?.map(v => v.orderId || v.afsOrderId), 'order打印完')
				printOrderList.value.splice(0, 1);
				console.log(printOrderList.value?.map(v => v.orderId || v.afsOrderId), 'order删除后')
				doingPrint()
			})
		} else {
			setPrint1(item, 'afs', true).then(() => {
				ConfirmAfsOrderPrint(item, '0')
				console.log(printOrderList.value?.map(v => v.orderId || v.afsOrderId), 'afs打印完')
				printOrderList.value.splice(0, 1);
				console.log(printOrderList.value?.map(v => v.orderId || v.afsOrderId), 'afs删除后')
				doingPrint()
			})
		}
	} else {
		isPrint.value = false;
	}
}

const stopAutoPlay = function () {
	if (time.value) {
		clearInterval(time.value);
		time.value = null;
	}
}

const playMp3 = function (mp3Path) {
	let currentIndex = 0;
	isMp3Played.value = true;
	const playNext = () => {
		console.warn('开始播报:isMp3Played.value ,currentIndex, mp3Path.length', isMp3Played.value, currentIndex, mp3Path.length, mp3Path);
		if (currentIndex < mp3Path.length) {
			let player = plus.audio.createPlayer(mp3Path[currentIndex]);
			player.play(() => {
				currentIndex++;
				player.close();
				playNext();
			});
			player.onerror = (error) => {
				console.error(`播放第${currentIndex + 1}首出错: ${error}`);
				currentIndex++;
				player.close();
				playNext();
			};
		} else {
			isMp3Played.value = false;
			console.log('播放结束');
		}
	};
	playNext();
}
const mergeArrays = function (list, arr) {
	let uniqueArr = Array.from(new Set([...list]));
	arr.map(v => {
		let item = list.findIndex(a => (a.type == v.type) && ((a.orderId === v.orderId) || (a
			.afsOrderId === v.afsOrderId)))
		if (item == -1) {
			uniqueArr.push(v)
		}
	})
	return uniqueArr
}

const inputChange = function (e) {
	rejectReason.value = e.detail.value;
}

const inputDeliveryChange = function (e) {
	orderDeliveryCancelReason.value = e.detail.value;
}

const closeDeliveryPopup = () => {
	showDeliveryPop.value = false;
	deliverList.value = []
}

const close = () => {
	showAuditSendAfsPopup.value = false
	showConfirmApplyOrderPopup.value = false;
	showCancelOrderPopup.value = false;
	showDeliveryCancelPopup.value = false;
	showOrderPickupPop.value = false;
	currentItem.value = {};
	orderItem.value = {};
	modalType.value = '';
	orderCancelReasonType.value = '';
	orderDeliveryCancelReason.value = '';
	orderDeliveryCancelReasonType.value = null;
	rejectReason.value = '';
	isOrderCancel.value = false;
}

const onSelectOrderType = function (item) {
	if (item.text == '搜订单') {
		toSearch('order')
	} else {
		toSearch('afs')
	}
}

const submitAuditSendAfs = function (data) {
	orderAction({
		uniqueKey: '售后单表',
		methodName: 'acceptAfsApplyOrder'
	}, orderItem.value, data, '退货退款上门取件设置成功！', true);
}

const selectStatus = (e) => {
	searchData.value.status = e;
	orderList.value = [];
	fetchAllSearchData()
}

const selectChnlType = (e) => {
	searchData.value.chnlType = e;
	orderList.value = [];
	fetchAllSearchData()
}

const selectSortType = (e) => {
	formData.value.sortType = e;
	pickingStore.setSortType(e)
	setTimeout(() => {
		BcmNavBar.value.closeDrawer()
	}, 100)
	fetch()
}

const selectItem = function (item) {
	orderCancelReasonType.value = item.detail.value;
}

const selectDeliveryCancelItem = function (item) {
	orderDeliveryCancelReasonType.value = item;
}

const changeDate = function (e) {
	searchData.value.startDate = e;
	searchData.value.endDate = e;
	orderList.value = [];
	fetchAllSearchData()
}

const swichTab = function () {
	orderType.value = orderType.value == 'on' ? "all" : 'on';
	orderList.value = [];
	if (orderType.value == 'all') {
		searchData.value = {
			chnlType: '',
			status: '',
			startDate: null,
			endDate: null,
		}
	} else {
		staOrderStatus();
		fetchOrderData();
	}
}

const changeTab1 = async function (index) {
	tabIndex.value = index;
	orderList.value = [];
	if (statusList.value[index].list.length == 0) {
		activeKey.value = {
			value: statusList.value[index].value,
			type: statusList.value[index].type
		}
	} else {
		activeKey.value = {
			value: statusList.value[index].list[0].value,
			type: statusList.value[index].list[0].type,
		}
	}
	formData.value.status = activeKey.value.value;
	await staOrderStatus();
	await fetchOrderData();
}

const changeTab = async function (value, type) {
	activeKey.value = {
		value,
		type
	}
	orderList.value = [];
	formData.value.status = value;
	await staOrderStatus();
	await fetchOrderData();
}
const fetch = async function () {
	orderList.value = []
	if (orderType.value == 'all') {
		await fetchAllSearchData()
	} else {
		await staOrderStatus();
		await fetchOrderData();
	}
}

const addressKey = computed(() => {
	return orderItem.value.afsrderStatus ? 'pickUpAddress' : 'consigneeAddress'
})

const popupOrderType = computed(() => {
	return orderItem.value.afsrderStatus ? 'afs' : 'order'
})

const popupTitleType = computed(() => {
	return orderItem.value.afsrderStatus ? '取件地址' : '顾客地址'
})

const setDefault = async () => {
	const mainStore = useMainStore();
	const { loginInfo } = mainStore;
	console.log(loginInfo?.sDefaultStore, 'loginInfo?.sDefaultStore')
	sUserStore.value = loginInfo?.sDefaultStore ? loginInfo.sDefaultStore : loginInfo.sUserStore;
	sUserStoreName.value = loginInfo?.sDefaultStoreName ? loginInfo.sDefaultStoreName : loginInfo.sUserStoreName;
	sUser.value = loginInfo.sUser;
	sUserMerchantCode.value = !!loginInfo?.merchantCode ? loginInfo?.merchantCode : loginInfo.sDefaultMerchantCode;
	sUserMerchantName.value = !!loginInfo?.merchantName ? loginInfo?.merchantName : loginInfo.sDefaultMerchantName;
	formData.value.sortType = sortType.value
}

const initDict = async () => {
	const bcmDictLists = getBcmDictLists(['chnlType', 'orderStatus', 'deliveryStatus', 'pickType', 'deliveryTimeType', 'logisticsCode', 'afsOrderStatus', 'afsOrderStatus', 'dealType', 'returnGoodsType', 'orderPrimaryStatus', 'performanceStatus']);
	chnlTypeDictList.value = bcmDictLists['chnlType'];
	orderStatusList.value = bcmDictLists['orderStatus'];
	deliveryStatusList.value = bcmDictLists['deliveryStatus'];
	pickTypeList.value = bcmDictLists['pickType'];
	deliveryTimeTypeList.value = bcmDictLists['deliveryTimeType'];
	logisticsCodeList.value = bcmDictLists['logisticsCode'];
	afsOrderStatusList.value = bcmDictLists['afsOrderStatus'];
	dealTypeList.value = bcmDictLists['dealType'];
	returnGoodsTypeList.value = bcmDictLists['returnGoodsType'];
	orderPrimaryStatusList.value = bcmDictLists['orderPrimaryStatus'];
	performanceStatusList.value = bcmDictLists['performanceStatus'];
}

const acceptAfsApplyOrder = async (dealType, v) => {
	orderAction({
		uniqueKey: '售后单表',
		methodName: 'acceptAfsApplyOrder'
	}, {}, {
		dealType,
		afsOrderId: v.afsOrderId
	}, '审核通过', true).then((res) => {
		if (dealType == '1' && !['2', '1'].includes(v.syncErpBreakageStatus) && showConfigModal) {
			uni.navigateTo({
				url: `/pages/BcmViews/PickingOrder/breakage?afsOrderId=` + v.afsOrderId + '&type=2'
			});
		}
	})
}

const orderAction = async function ({
	uniqueKey,
	methodName
}, v, params = undefined, text = '', popup = false, fn = undefined) {
	service.enjoyShowLoading('正在加载...');
	let param = {
		chnlCode: v.chnlCode,
		chnlType: v.chnlType,
		orderNo: v.orderNo,
		storeCode: v.storeCode,
		thirdOrderNo: v.thirdOrderNo,
		orderId: v.orderId,
		afsOrderId: v.afsOrderId,
		...params,
	}
	const response = await bcmRequest(bcmUrl.orderApi, uniqueKey, methodName, param);
	service.enjoyHideLoading();
	if (text) {
		uni.showToast({
			title: text,
			icon: 'none'
		});
	}
	if (popup) {
		close()
	}
	await fetch()
	if (fn) {
		fn(v)
	}
	if (params) {
		return response
	}
}

// 选择框点击事件
const clickStore = () => {
	let parms = Enjoy.GetDialogParms();
	parms.CallBack = SelectionChanged;
	parms.SelectionType = "机构选择";
	parms.SelectedItems = sUserStore.value;
	Enjoy.OpenDialog(parms)
}

const showUserMerchantModal = () => {
	uni.navigateTo({
		url: '/pages/BcmViews/modals/merchant/index'
	})
}

const SelectionChanged = (event) => {
	if (event.SelectionType == '机构选择') {
		// 更新机构信息
		let sUserStoreHier = event.BackParms.Type; //层级
		sUserStoreName.value = event.BackParms.Value;
		sUserStore.value = event.BackParms.Key;
		if (WsRef.value && service.getStorageSync('pushMode') != '1') {
			WsRef.value.send({
				data: JSON.stringify({ storeCode: event.BackParms.Key, terminalType: "APP", terminalId: BcmPrintTerminalId.value })
			})
		}
		uni.$emit(BcmEventType.SWITCH_STORE, { msg: '切换门店' });
		mainStore.switchStore(sUserStoreHier, sUserStore.value, sUserStoreName.value);

		// 按新条件获取数据
		fetchOrderData();
		staOrderStatus();
	} else if (event.type == 'exchange') {
		if (event.result) {
			close()
		}
	} else if (event.type == 'userMerchant') {
		if (event.merchantInfo) {
			mainStore.setUserCurMerchantInfo(event.merchantInfo);
			uni.$emit(BcmEventType.SWITCH_MERCHANT, { msg: '切换商户' });
			sUserMerchantCode.value = event.merchantInfo.merchantCode;
			sUserMerchantName.value = event.merchantInfo.merchantName;
			// 按新条件获取数据
			fetchOrderData();
			staOrderStatus();
		}
	}
}

const scanCode = function () {
	uni.scanCode({
		scanType: ['qrCode'],
		// 是否启动自动识别字符编码功能
		autoDecodeCharset: true,
		autoZoom: false,
		success: function (res) {
			if (res.result != '' && res.result != undefined && res.result != null) {
				uni.navigateTo({
					url: './search?searchText=' + res.result
				});
			}
		},
	});
}
// 列表下拉刷新
const listPullDown = (e) => {
	if (orderType.value == 'all') {
		fetchAllSearchData()
	} else {
		fetchOrderData();
		staOrderStatus();
	}
}

// 列表上拉加载
const listPullUp = (e) => {
	if (CurrentPage.value < PageCount.value) {
		CurrentPage.value = CurrentPage.value + 1;
		if (orderType.value == 'all') {
			fetchAllSearchData(true)
		} else {
			fetchOrderData(true);
		}
	}
}

const toSearch = function (type) {
	if (type == 'order') {
		uni.navigateTo({
			url: './search'
		})
	} else {
		uni.navigateTo({
			url: './afssearch'
		})
	}
}

const deliveryCancelSure = () => {
	if (billType.value == '1') {
		orderAction({
			uniqueKey: '订单表',
			methodName: 'CancelDelivery'
		}, orderItem.value, {
			orderDeliveryCancelReason: orderDeliveryCancelReasonType.value?.mustInputFlag == '1' ? orderDeliveryCancelReason.value : orderDeliveryCancelReasonType.value?.name,
			orderDeliveryCancelReasonType: orderDeliveryCancelReasonType.value?.code
		}, '取消配送操作成功', true);
	} else {
		orderAction({
			uniqueKey: '售后单表',
			methodName: 'CancelDelivery'
		}, orderItem.value, {
			afsOrderDeliveryCancelReason: orderDeliveryCancelReasonType.value?.mustInputFlag == '1' ? orderDeliveryCancelReason.value : orderDeliveryCancelReasonType.value?.name,
			afsOrderDeliveryCancelReasonType: orderDeliveryCancelReasonType.value?.code
		}, '退货配送取消成功', true);
	}
}

const getChnlType = async function () {
	let chnlList = [];
	const response = await bcmRequest(bcmUrl.managerApi, '渠道列表', 'SearchDistinctChannelWithType', {});
	await Promise.all(response.map(v => {
		if (getBcmDictItem('chnlType', v.chnlType)) {
			chnlList.push(getBcmDictItem('chnlType', v.chnlType))
		}
	}))
	chnlTypeList.value = chnlList;
}

const fetchNewOrderNum = async function () {
	let list = [];
	const response = await bcmRequest(bcmUrl.orderApi, '订单表', 'StatisticsByOrderStatus', {
		WhereList: [{
			c_col: "storeCode",
			c_oper: "等于",
			c_value: sUserStore.value,
			c_logic: "而且"
		}, {
			c_col: 'orderStatus',
			c_oper: '包含',
			c_logic: '而且',
			c_value: '1,2,3,4,5,25,9'
		}]
	});
	list = response.ReturnObject.filter(v => (v.status == '1' || v.status == '9'));
	let afsOrderResponse = await bcmRequest(bcmUrl.orderApi, '售后单表', 'StatisticsByAfsOrderStatus', {
		WhereList: [{
			c_col: "storeCode",
			c_oper: "等于",
			c_value: sUserStore.value,
			c_logic: "而且"
		}, {
			c_col: 'afsOrderStatus',
			c_oper: '包含',
			c_logic: '而且',
			c_value: '10,12,17'
		}]
	});
	afsOrderResponse.ReturnObject.forEach(v => {
		list.push({
			status: v.status,
			number: v.number
		})
	})
	return list
}
const staOrderStatus = async function () {
	if (performanceStatusList.value.length > 0) {
		let list = [],
			orderWhereList = [{
				c_col: "storeCode",
				c_oper: "等于",
				c_value: sUserStore.value,
				c_logic: "而且"
			}, {
				c_col: "chnlType",
				c_oper: "等于",
				c_value: formData.value.chnlType,
				c_logic: "而且"
			}, {
				c_col: "merchantCode",
				c_oper: "等于",
				c_value: sUserMerchantCode.value,
				c_logic: "而且"
			}, {
				c_col: 'orderStatus',
				c_oper: '包含',
				c_logic: '而且',
				c_value: '1,2,3,4,5,25,9'
			}],
			afsOrderWhereList = [{
				c_col: "storeCode",
				c_oper: "等于",
				c_value: sUserStore.value,
				c_logic: "而且"
			}, {
				c_col: "merchantCode",
				c_oper: "等于",
				c_value: sUserMerchantCode.value,
				c_logic: "而且"
			}, {
				c_col: "chnlType",
				c_oper: "等于",
				c_value: formData.value.chnlType,
				c_logic: "而且"
			}, {
				c_col: 'afsOrderStatus',
				c_oper: '包含',
				c_logic: '而且',
				c_value: '10,12,17'
			}];
		const response = await bcmRequest(bcmUrl.orderApi, '订单表', 'StatisticsByOrderStatus', {
			WhereList: formData.value.orderNo ? [{
				c_col: "number",
				c_oper: "等于",
				c_value: formData.value.orderNo,
				c_logic: "而且"
			}] : orderWhereList
		});
		list = response.ReturnObject;
		let afsOrderResponse = await bcmRequest(bcmUrl.orderApi, '售后单表', 'StatisticsByAfsOrderStatus', {
			WhereList: formData.value.orderNo ? [{
				c_col: "number",
				c_oper: "等于",
				c_value: formData.value.orderNo,
				c_logic: "而且"
			}] : afsOrderWhereList
		});
		afsOrderResponse.ReturnObject.forEach(v => {
			list.push({
				afsStatus: v.status,
				number: v.number
			})
		})
		await getOrderStatus(list)
	}
}
//状态格式化
const getOrderStatus = async function (ab) {
	let chnlList = [],
		firstLevel = [];
	orderPrimaryStatusList.value?.forEach((v) => {
		let f = {
			text: v.text,
			number: 0,
			value: v.value,
			type: v.pdict == 'order' ? 0 : (v.value.indexOf(',') == -1 ? 1 : 2),
			list: []
		};
		if (v.value.indexOf(',') != -1) {
			f.list.push({
				text: '全部',
				number: 0,
				value: v.value,
				type: v.pdict == 'order' ? 0 : (v.value.indexOf(',') == -1 ? 1 : 2)
			})
		}
		firstLevel.push(f)
	})

	performanceStatusList.value.filter(v => !['7', '8'].includes(v.value)).forEach((v,
		i) => {
		if (v?.pdict == 'order') {
			v.type = 0;
			let item = ab?.find(n => n.status == v.value);
			v.number = item ? item?.number : 0;
		} else {
			if (v.value.indexOf(',') == -1) {
				v.type = 1;
				let item = ab?.find(n => n.afsStatus == v.value);
				v.number = item ? item?.number : 0;
			} else {
				v.type = 2;
				let number = v.value.split(',');
				let b = 0;
				let c = ab?.filter(a => {
					if (a.afsStatus == number[0] || a.afsStatus == number[1]) {
						return a
					}
				});
				c?.forEach(n => b += (n.number * 1))
				v.number = b;
			}
		}
		chnlList.push(v)

		let index = firstLevel.findIndex(a => a.value?.split(',')?.includes(v.value) || (a.value
			.indexOf('12,17') != -1));
		if (index != -1 && firstLevel[index].list.length != 0) {
			firstLevel[index].list.push({
				text: v.text,
				number: v.number,
				type: v.type,
				value: v.value
			})
		}
		if (index != -1 && firstLevel[index].list.length == 0) {
			firstLevel[index].number = v.number;
		}
	})

	firstLevel.forEach(v => {
		v.list?.forEach(n => v.number += (n.number * 1))
	})

	if (chnlList.length != 0) {
		statusList.value = firstLevel;
	}
}
//查询订单
const fetchOrderData = async function (e = undefined) {
	service.enjoyShowLoading('正在加载...');
	if (!e) {
		CurrentPage.value = 1;
	}
	let whereList = [{
		c_col: "storeCode",
		c_oper: "等于",
		c_value: sUserStore.value,
		c_logic: "而且"
	}, {
		c_col: "chnlType",
		c_oper: "等于",
		c_value: formData.value.chnlType,
		c_logic: "而且"
	}, {
		c_col: "merchantCode",
		c_oper: "等于",
		c_value: sUserMerchantCode.value,
		c_logic: "而且"
	}, {
		c_col: "sortType",
		c_oper: "等于",
		c_value: formData.value.sortType,
		c_logic: "而且"
	}];
	if (formData.value.startDate || formData.value.endDate) {
		let arr = [];
		!!formData.value.startDate && arr.push({
			c_col: "time",
			c_oper: "大于等于",
			c_value: formData.value.startDate,
			c_col_dtype: "System.DateTime",
			c_logic: "而且"
		});

		!!formData.value.endDate && arr.push({
			c_col: "time",
			c_oper: "小于等于",
			c_value: formData.value.endDate,
			c_col_dtype: "System.DateTime",
			c_logic: "而且"
		})
	}
	const param = {
		IsNotPage: false,
		CurrentPage: CurrentPage.value,
		PageSize: PageSize.value,
		WhereList: formData.value.orderNo ? [{
			c_col: "number",
			c_oper: "等于",
			c_value: formData.value.orderNo,
			c_logic: "而且"
		}] : whereList
	}
	let typeItem = tabIndex.value === 3 ? statusList.value[tabIndex.value] : statusList.value[tabIndex.value]?.list.find(v => v.value == activeKey.value.value);
	formData.value.status = typeItem.value;
	if (formData.value.status.indexOf(',') === -1) {
		param.WhereList.push({
			c_col: 'status',
			c_oper: '等于',
			c_value: formData.value.status,
			c_logic: "而且"
		})
	} else {
		param.WhereList.push({
			c_col: 'status',
			c_oper: '包含',
			c_value: formData.value.status,
			c_logic: "而且"
		})
	}
	let uniqueKey = (typeItem.type !== 1 && typeItem.type !== 2) ? '订单表' : '售后单表';
	const response = await bcmRequest(bcmUrl.orderApi, uniqueKey, (uniqueKey === '订单表' || !uniqueKey) ?
		'QueryOrderList' :
		'QueryAfsOrderList', param);
	service.enjoyHideLoading();
	CurrentPage.value = response.CurrentPage; //第几页
	PageSize.value = response.PageSize; //每页10条
	RowsCount.value = response.RowsCount; //总条数
	PageCount.value = response.PageCount; //总页数

	if (response.CurrentPage === 1) {
		orderList.value = response.ReturnObject;
	} else {
		orderList.value = orderList.value.concat(response.ReturnObject);
	}
}
const fetchAllSearchData = async function (e = undefined) {
	service.enjoyShowLoading('正在加载...');
	if (!e) {
		CurrentPage.value = 1;
	}
	let whereList = [{
		c_col: "storeCode",
		c_oper: "等于",
		c_value: sUserStore.value,
		c_logic: "而且"
	}, {
		c_col: "chnlType",
		c_oper: "等于",
		c_value: searchData.value.chnlType,
		c_logic: "而且"
	}, {
		c_col: "merchantCode",
		c_oper: "等于",
		c_value: sUserMerchantCode.value,
		c_logic: "而且"
	}, {
		c_col: "sortType",
		c_oper: "等于",
		c_value: formData.value.sortType,
		c_logic: "而且"
	}];

	if (searchData.value.startDate) {
		whereList.push({
			c_col: "time",
			c_oper: "大于等于",
			c_value: searchData.value.startDate,
			c_col_dtype: "System.DateTime",
			c_logic: "而且"
		}, {
			c_col: "time",
			c_oper: "小于等于",
			c_value: searchData.value.startDate,
			c_col_dtype: "System.DateTime",
			c_logic: "而且"
		});
	}
	if (searchData.value.status) {
		if (searchData.value.status.indexOf(',') != -1) {
			whereList.push({
				c_col: 'status',
				c_oper: '包含',
				c_value: searchData.value.status,
				c_logic: "而且"
			})
		} else {
			whereList.push({
				c_col: 'status',
				c_oper: '等于',
				c_value: searchData.value.status,
				c_logic: "而且"
			})
		}
	}

	const param = {
		IsNotPage: false,
		CurrentPage: CurrentPage.value,
		PageSize: PageSize.value,
		WhereList: whereList
	}

	const response = await bcmRequest(bcmUrl.orderApi, '订单表',
		'QueryOrderList', param);
	service.enjoyHideLoading();
	CurrentPage.value = response.CurrentPage; //第几页
	PageSize.value = response.PageSize; //每页10条
	RowsCount.value = response.RowsCount; //总条数
	PageCount.value = response.PageCount; //总页数
	if (response.CurrentPage == 1) {
		orderList.value = response.ReturnObject;
	} else {
		orderList.value = orderList.value.concat(response.ReturnObject);
	}
}

watch(() => bcmConfig.value, (newVal) => {
	if (newVal) {
		showConfigModal.value = getBcmConfigValue() == '1' || false;
	}
}, { immediate: true });

const initStore = async () => {
	if (!loginInfo.sUserStore) {
		setTimeout(() => {
			BcmNavBar.value.onClickStore();
		}, 100)
		return;
	}
	await setDefault();
}

onLoad(async () => {
	await initStore()
	// initTerminalId()
	//connectWebSocket();
	uni.$on(BcmEventType.REFRESH_ORDER_LIST, () => {
		debounce(2);
	})

})

onShow(async () => {
	await init();
	chnlTypeList.value.length === 0 && getChnlType()
	await initDict();
	await initStore();
	showMessage.value = false;
	showMessageValue.value = '';
	if (!bluetoothPrinter.value?.deviceId) {
		showMessage.value = true
		let text = '未连接打印机';
		showMessageValue.value = showMessageValue.value != '' ? (showMessageValue.value + ' | ' + text) : text;
	}

	if (!autoPrint.value) {
		showMessage.value = true
		let text1 = '未设置自动打印';
		showMessageValue.value = showMessageValue.value != '' ? (showMessageValue.value + ' | ' + text1) : text1;
	}

	if (!!sUserStore.value) {
		if (service.getStorageSync('pushMode') == '1') {
			checkAutoPlay()
		}
		startTimer()
		if (!uni.getStorageSync('ispreviewImage')) {
			orderType.value !== 'all' && changeTab(activeKey.value?.value, activeKey.value?.type)
		}
		uni.setStorageSync('ispreviewImage', false)
	}
	if (orderType.value === 'all') {
		orderList.value = []
		fetchAllSearchData()
	} else {
		searchData.value = {
			chnlType: '',
			status: '',
			startDate: null,
			endDate: null,
		}
	}
})

onUnmounted(() => {
	stopTimer()
	stopHeartbeat()
	stopAutoPlay()
	if (WsRef.value) {
		WsRef.value?.close();
	}
	uni.$off(BcmEventType.REFRESH_ORDER_LIST)
})

defineExpose({
	SelectionChanged
})

</script>
<style lang="scss" scoped>
@import "@/static/font/enjoyicon/iconfont.css";
@import "../common/common.css";

.navigation {
	display: flex;
	flex-direction: column;
	width: 100%;
	height: 100vh;
	background: #f2f2f2;
}

.top-view {
	width: 100%;
	background: #fff;
}

.main-view {
	flex-direction: column;
	flex: 1;
}

.footer-view {
	height: 100%;
	background: #f1f1f1;
}

::v-deep .white-main {
	right: 0;
	left: 0;
}

.on {
	color: rgba(2, 183, 230, 1);
	font-weight: bold;
}

.on1 {
	color: #fff;
	font-weight: bold;
	background: linear-gradient(159deg, #4fe0ea 0%, #85b6fd 100%);
	border-radius: 26rpx;
}

.border {
	position: absolute;
	bottom: 0rpx;
	left: 58rpx;
	width: 36rpx;
	height: 12rpx;
	background-color: transparent;
	border-bottom: none;
}

.content-img {
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	align-items: stretch;
	flex: 1;
}

.footer {
	flex: 1;
	box-sizing: border-box;
	padding: 0;
	margin: 0;
	background-color: #fff;

	::v-deep .m-card-template {
		display: block;
		padding: 0;
		margin: 0;
	}
}

.bottom {
	display: flex;
	justify-content: space-between;
	flex: 0 0 auto;
	height: 70rpx;
	padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
	background: $uni-bg-color;
}

.bottom-1 {
	display: flex;
	justify-content: center;
	flex: 0 0 auto;
	height: 70rpx;
	padding: $uni-spacing-col-sm * 2 $uni-spacing-row-sm;
	background: $uni-bg-color;
}

.search {
	::v-deep .uni-date-x {
		height: 40rpx;
		color: #000;
		font-size: 21rpx;
	}
}

.popup-content {
	display: flex;
	flex-direction: column;
	width: 100%;
	padding: 0;
	background-color: #fff;

	.popup-title {
		display: flex;
		align-items: center;
		box-sizing: border-box;
		width: 100%;
		height: 100rpx;
		padding-right: 36rpx;
		padding-left: 30rpx;
		font-size: 33rpx;
		line-height: 100rpx;
		border-bottom: 1px solid #f1f1f1;
	}

	textarea {
		box-sizing: border-box;
		width: 100%;
		height: 80px;
		padding: 5px;
		margin: 5px 0;
		border: 1px solid #ccc;
		border-radius: 5px;
	}
}

.container {
	box-sizing: border-box;
	width: 100%;
	height: 90rpx;
	color: #000;
	background-color: #fff;
}

.container1 {
	box-sizing: border-box;
	width: 100%;
	height: 90rpx;
	padding-left: 34rpx;
	color: #000;
	background-color: #fff;
}

.scroll-view {
	display: flex;
	align-items: center;
	box-sizing: border-box;
	overflow-x: auto;
	width: 100%;
	height: 100%;
	white-space: nowrap;
}

.item {
	position: relative;
	display: inline-block;
	box-sizing: border-box;
	width: 150rpx;

	// padding: 0 20rpx;
	height: 70rpx;
	margin-top: 20rpx;

	// border-bottom: 6rpx solid #fff;
	font-size: 16px;
	line-height: 50rpx;
	text-align: center;
	text-align: center;
}

.item1 {
	position: relative;
	display: inline-block;
	box-sizing: border-box;
	height: 48rpx;
	padding: 0 20rpx;
	margin-top: 24rpx;
	margin-right: 15rpx;
	font-size: 14px;
	line-height: 48rpx;
	text-align: center;
	text-align: center;
}

.number {
	position: absolute;
	top: -12rpx;
	right: 10rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	box-sizing: border-box;
	min-width: 32rpx;
	height: 32rpx;
	padding: 8rpx;
	color: #fff;
	font-size: 26rpx;
	background-color: #f00;
	border-radius: 32rpx;
}

.number1 {
	position: absolute;
	top: -12rpx;
	right: -15rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	box-sizing: border-box;
	min-width: 32rpx;
	height: 32rpx;
	padding: 8rpx;
	color: #fff;
	font-size: 26rpx;
	background-color: #f00;
	border-radius: 32rpx;
}

.m-card-arrow {
	color: $uni-text-color-disable !important;
}

.m-card-arrowright {
	margin-left: 10rpx;
}

::v-deep .list_cell {
	overflow: visible;
	padding-bottom: 14rpx;
	margin: 20rpx 20rpx 0;
}

.selector-view {
	width: 170%;
}

::v-deep .uni-select__selector-item uni-text,
::v-deep .uni-select__selector-item span {
	white-space: nowrap;
}

::v-deep .uni-select__selector {
	width: auto !important;
}
</style>